//
//  PaperReturnViewManager.m
//  ZYOnlineSchool
//
//  Created by 毕武侠 on 2017/3/1.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "PaperReturnViewManager.h"
#import "PaperModuleModel.h"

@interface PaperReturnViewManager ()

@property (nonatomic, strong, readwrite) RACSubject *exitSignal;  // 退出Signal
@property (nonatomic, strong) UIAlertView *alertView;

@end

@implementation PaperReturnViewManager

- (void)setupConfigure {
    self.exitSignal = [RACSubject subject];
}

- (void)setBackSignal:(RACSignal *)backSignal {
    _backSignal = backSignal;
    
    [_backSignal subscribeNext:^(id x) {
        [self setupBackData];
    }];
}

- (void)setupBackData {
    if (self.datas.count == 0 || self.isAllowAnswer == NO) {                // 没有数据，直接退出
        [self.exitSignal sendNext:nil];
    } else {
        __block NSUInteger selectIndex = 0;
        __block NSUInteger allIndex = 0;
        
        [self.datas enumerateObjectsUsingBlock:^(PaperModuleModel *moduleModel, NSUInteger idx, BOOL * _Nonnull stop) {
            allIndex += moduleModel.module_question.count;
            
            [moduleModel.module_question enumerateObjectsUsingBlock:^(PaperBaseModel * model, NSUInteger idx, BOOL * _Nonnull stop) {
                if ((model.ques_model == 0 || model.ques_model == 2) && model.index != NSNotFound) {
                    selectIndex++;
                } else if ((model.ques_model == 1 || model.ques_model == 3) && model.index > 0) {
                    selectIndex++;
                }
            }];
        }];
        
        if (selectIndex == 0) {
            [self.exitSignal sendNext:nil];    // 有数据，但未作答，直接退出
        } else {
            if (selectIndex == allIndex) {
                self.alertView.message = @"您已全部作答完成，确定要退出本次答题？";
            } else {
                self.alertView.message = [NSString stringWithFormat:@"您尚有%ld题未答，是否退出本次答题？", allIndex - selectIndex];
            }
            [self.alertView show];
        }
    }
}

- (UIAlertView *)alertView {
    if (_alertView == nil) {
        _alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _alertView;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex) {
        [self.exitSignal sendNext:nil];         // 有数据，作答了几道题，但仍然退出
    }
}

@end
